package com.ihrm.system.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.utils.JwtUtil;
import com.ihrm.domain.company.response.UserResult;
import com.ihrm.domain.system.User;
import com.ihrm.domain.system.response.ProfileResult;
import com.ihrm.system.client.DepartmentFeignClient;
import com.ihrm.system.service.PermissionService;
import com.ihrm.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/sys")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private JwtUtil jwtUtils;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private DepartmentFeignClient departmentFeignClient;
	/**
	 * 测试Feign组件
	 * 调用系统微服务的test接口传递部门id,通过feign调用部门微服务获取部门信息
	 */
	@GetMapping("/test/{id}")
	 public Result testFeign(@PathVariable("id")  String id) {
		Result result = departmentFeignClient.findById(id);
		return result;
	}



	/**
	 * 添加用户
	 */
	@PostMapping("/user")
	public Result add(@RequestBody User user) {
		//设置保存的企业id
		user.setCompanyId(companyId);
		user.setCompanyId(companyName);
		userService.save(user);
		return Result.SUCCESS();
	}

	/**
	 * 根据id查询用户
	 */
	@GetMapping("/user/{userId}")
	public Result findById(@PathVariable(value = "userId") String id) {
		//添加 roleIds(用户已经具有的角色id数组)
		User user = userService.findById(id);
		UserResult userResult = new UserResult(user);
		return new Result(ResultCode.SUCCESS,userResult);
	}

	/**
	 * 根据id更新用户
	 */
	@PutMapping("/user/{userId}")
	public Result update(@PathVariable(value = "userId") String id, @RequestBody User user) {
		user.setId(id);
		userService.update(user);
		return Result.SUCCESS();
	}

	/**
	 * 查询所有用户列表
	 */
	@GetMapping("/user")
	public Result findAll(int page, int size, @RequestParam() Map<String,Object>  map) {
		//1.指定企业id
		map.put("companyId", companyId);
		Page<User> pageUser= userService.findAll(map, page, size);
		//构造返回结果
		PageResult<User> pageResult = new PageResult<>(pageUser.getTotalElements(),pageUser.getContent());
		return new Result(ResultCode.SUCCESS,pageResult);
	}

	/**
	 * 根据id删除用户
	 */
	@RequiresPermissions("user:delete")
	@DeleteMapping(value = "/user/{userId}",name="user:delete")
	public Result delete(@PathVariable(value = "userId") String id) {
		userService.deleteById(id);
		return Result.SUCCESS();
	}

	/**
	 * 分配角色
	 *
	 *
	 */
	@PutMapping("/user/assignRoles")
	public Result assignRoles(@RequestBody Map<String, Object> map) {
		//1.获取到被分配的用户id
		String userId=(String) map.get("id");
		//2.获取角色的id列表
		List< String> roleIds= (List<String>) map.get("roleIds");
		//3.调用service完成角色分配
		userService.assignRoles(userId,roleIds);
		return Result.SUCCESS();
	}

/*	public static void main(String[] args) {
		String password = new Md5Hash("123456","13800000003",3).toString();
		System.out.println(password);
	}*/

	/**
	 * 用户登录
	 * 1.通过service根据mobile查询用户
	 * 2.比较密码
	 * 3.生成jwt
	 */
	@PostMapping("/login")
	public Result login(@RequestBody Map<String,String> loginMap) {
		String mobile = loginMap.get("mobile");
		String password = loginMap.get("password");

		try {


			//对密码加密
			password = new Md5Hash(password, mobile,3).toString();//密码，盐，加密次数
			//1.构造登录令牌UsernameAndPasswordToken
			UsernamePasswordToken token = new UsernamePasswordToken(mobile,password);
			//2.获取subject
			Subject subject = SecurityUtils.getSubject();
			//3.调用login方法,进入realm完成认证
			subject.login(token);
			//4.获取sessionId
			String sessionId = (String) subject.getSession().getId();
			return new Result(ResultCode.SUCCESS,sessionId);
		} catch (Exception e) {
			return new Result(ResultCode.MOBILEORPASSWORDERROR);
		}

/*		User user = userService.findByMobile(mobile);
		if(user==null||!user.getPassword().equals(password)){
			return new Result(ResultCode.MOBILEORPASSWORDERROR);
		}else{
			//登陆成功
			//api权限字符串
			StringBuilder sb = new StringBuilder();
			//获取到所有的可访问api权限
			for(Role role: user.getRoles()){
				for(Permission permission: role.getPermissions()){
					if(permission.getType()== PermissionConstants.PY_API){
						sb.append(permission.getCode()).append(",");
					}
				}
			}

			Map<String,Object> map = new HashMap<>();
			map.put("apis",sb.toString());//可访问的api权限字符串
			map.put("companyId",user.getCompanyId());
			map.put("companyName",user.getCompanyName());
			String token = jwtUtils.createJwt(user.getId(), user.getUsername(), map);
			return new Result(ResultCode.SUCCESS,token);*/
	}


/**
 * 用户成功登录之后，获取用户信息
 *   1.获取用户id
 *   2.根据用户id查询用户信息
 *   3.构建返回值对象，响应数据返回
 * @return
 */
@PostMapping("/profile")
public Result profile(HttpServletRequest  request) throws Exception {
	/**
	 * 1.从请求头中获取token数据
	 *  1.1 获取请求头Authorization Bearer token
	 *  1.2 替换Bearer+空格
	 *  1.3 解析token
	 * 2.获取claims
	 */
/*		String authorization = request.getHeader("Authorization");
		if(StringUtils.isEmpty(authorization)){
			throw new CommonException(ResultCode.UNAUTHENTICATED);
		}
		String token = authorization.replace("Bearer ", "");
		//获取claims
		Claims claims = jwtUtils.parseJwt(token);*/

	//获取session中的安全数据
	Subject subject = SecurityUtils.getSubject();
	PrincipalCollection principals = subject.getPrincipals();
	ProfileResult profileResult = (ProfileResult) principals.getPrimaryPrincipal();
/*	String userId = claims.getId();
	//获取用户信息
	User user = userService.findById(userId);

	//根据不同的用户级别获取不同的权限
	ProfileResult profileResult = null;

	if("user".equals(user.getLevel())){
		profileResult = new ProfileResult(user);
	}else{
		Map map =new HashMap();
		if("coAdmin".equals(user.getLevel())){
			map.put("enVisible","1");
		}
		List<Permission> permissionList = permissionService.findAll(map);
		profileResult= new ProfileResult(user,permissionList);
	}*/

	return new Result(ResultCode.SUCCESS,profileResult);
}
}
